package com.sinohb.autonomousdriving_test;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static boolean UseWindowOverlay = false ;

    private static final int PERMISSION_REQUEST_CODE = 123;
    private boolean m_isHandlingPermission = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        tv.setText("Startup Page, entering...");

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
        Log.i("ScreenSize", "ScreenSize: " + displayMetrics.widthPixels + "x" + displayMetrics.heightPixels);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {// R:30:Android11
            if (!Environment.isExternalStorageManager()) {
                m_isHandlingPermission = true;
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            } else {
                startRendering();
            }
            return;
        }

        if (checkPermissions()) {
            // 权限已被授予，执行需要该权限的操作
            Log.i("Permission", "already permission passed");
            startRendering();
        } else {
            // 请求权限
            requestPermissions();
        }
    }

    private void startRendering() {
        if (UseWindowOverlay) {
            if (!Settings.canDrawOverlays(this)) {
                m_isHandlingPermission = true;
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            } else {
                startService(new Intent(this, FloatingViewService.class));
            }
            return;
        }
        Intent intent = new Intent(this, RendererActivity.class);
        startActivity(intent);
        finish();
    }

    // 处理权限请求的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被用户授予，执行需要该权限的操作
                Log.i("Permission", "PERMISSION_GRANTED");
            } else {
                // 权限被拒绝，告知用户可能的影响或退出操作
                // 可以在这里向用户显示解释信息或采取其他措施
                Log.e("Permission", "PERMISSION not granted!");
            }
        }
    }

    // 检查权限是否已经被授予
    private boolean checkPermissions() {
        boolean canRead = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED;
        boolean canWrite = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED;
        boolean canUseInternet = ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET)
                == PackageManager.PERMISSION_GRANTED;
        return canRead && canWrite && canUseInternet;
    }

    // 请求权限
    private void requestPermissions() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET},
                PERMISSION_REQUEST_CODE);
    }

    private void printScreenResolution() {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int widthPixels = displayMetrics.widthPixels;   // 屏幕宽度（像素）
        int heightPixels = displayMetrics.heightPixels; // 屏幕高度（像素）
        float density = displayMetrics.density;         // 屏幕密度（比例因子，如 1.0、1.5、2.0）

        Log.d("ScreenResolution", "Width: " + widthPixels + "px");
        Log.d("ScreenResolution", "Height: " + heightPixels + "px");
        Log.d("ScreenResolution", "Density: " + density);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (m_isHandlingPermission) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    m_isHandlingPermission = false;
                    startRendering();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finishAffinity();
        System.exit(0);
    }
}